package org.zoomdev.zoom.common.caster;

/**
 * If A can cast to B
 * And B can cast to C
 * <p>
 * You can register like this
 * <p>
 * Caster.register(  A.class,C.class,new CasterBridge( A.class,B.class,C.class )  )
 */
class CasterBridge implements ValueCaster {

    private final ValueCaster toDestType;
    private final ValueCaster toBridgeType;

    /**
     * 现将 srcType转 bridgeType, 然后将 bridgeType转destType
     *
     * @param srcType
     * @param bridgetType
     * @param destType
     */
    CasterBridge(Class<?> srcType, Class<?> bridgetType, Class<?> destType) {
        this.toBridgeType = Caster.get(srcType, bridgetType);
        this.toDestType = Caster.wrap(bridgetType, destType);
    }

    /**
     * toBridgeTypeCaster 将转 输入类型为 bridgeType
     *
     * @param toBridgeTypeCaster
     * @param bridgetType
     * @param destType
     */
    CasterBridge(ValueCaster toBridgeTypeCaster, Class<?> bridgetType, Class<?> destType) {
        this.toDestType = Caster.wrap(bridgetType, destType);
        this.toBridgeType = toBridgeTypeCaster;
    }

    @Override
    public Object to(Object src) {
        //src to bridget
        Object value = toBridgeType.to(src);
        //bridget to dest
        return toDestType.to(value);
    }
}
